import json
import requests
from pydantic import BaseModel

class Food_model(BaseModel):
    food: str

def chinafcd(obj):
    if None == obj or {} == obj: return {}
    food = obj.food
    if None == food or "" == food: return {}
    data = {
        "categoryOne": (None, "0"),
        "categoryTwo": (None, "0"),
        "foodName": (None, food),
        "pageNum": (None, "1"),
        "field": (None, "0"),
        "flag": (None, "0")
    }
    url = "https://fq.chinafcd.org/FoodInfoQueryAction!queryFoodInfoList.do"
    resp = requests.post(url, files = data)
    status_code = resp.status_code
    if 200 != status_code:
        return {"error": status_code, "src": "chinafcd"}
    rdata = json.loads(resp.text)
    totalPages = rdata["totalPages"]
    tdata = rdata["list"]
    for i in range(2, totalPages + 1):
        data["pageNum"] = (None, str(i))
        resp = requests.post(url, files = data)
        status_code = resp.status_code
        if 200 != status_code:
            return {"error": status_code, "src": "chinafcd"}
        rdata = json.loads(resp.text)
        tdata += rdata["list"]
    result = {}
    keys = ["食部(Edible)", "水分(Water)", "能量(Energy)", "蛋白质(Protein)", "脂肪(Fat)", "胆固醇(Cholesterol)", "灰分(Ash)", "碳水化合物(CHO)", "总膳食纤维(Dietary fiber)", "胡萝卜素(Carotene)", "维生素A(Vitamin)", "α-TE", "硫胺素(Thiamin)", "核黄素(Riboflavin)", "烟酸(Niacin)", "维生素C(Vitamin C)", "钙(Ca)", "磷(P)", "钾(K)", "钠(Na)", "镁(Mg)", "铁(Fe)", "锌(Zn)", "硒(Se)", "铜(Cu)", "锰(Mn)", "碘(I)", "饱和脂肪酸(SFA)", "单不饱和脂肪酸(MUFA)", "多不饱和脂肪酸(PUFA)"]
    for i in tdata:
        item = {}
        for j in range(len(keys)):
            item[keys[j]] = i[j + 5]
        result[i[2]] = item
    return result

